package com.example.test.thread;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @Description: Executors.newSingleThreadExecutor()：创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。
 * @Author: 明天
 * @CreateDate: 2019/1/17$ 14:42$
 * @UpdateDate: 2019/1/17$ 14:42$
 * @UpdateRemark: 修改内容
 * @Version: 1.0
 * 参考地址：https://www.toutiao.com/a6646938191863480835/?tt_from=weixin&utm_campaign=client_share&wxshare_count=1&timestamp=1547701010&app=news_article&utm_source=weixin&iid=57315554767&utm_medium=toutiao_android&group_id=6646938191863480835
 */
public class SingleThreadExecutor {
    public static void main(String[] args) {
        //创建一个单线程化的线程池
        ExecutorService singleThreadExecutor = Executors.newSingleThreadExecutor();
        for (int i=0;i<10;i++) {
            final int index=i;
            singleThreadExecutor.execute(new Runnable() {
                @Override
                public void run() {
                    try {
                        //结果依次输出，相当于顺序执行各个任务
                        System.out.println(Thread.currentThread().getName()+"正在被执行，打印的值是:"+index);
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            });
        }


    }
}
